<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Index | Craft and talk</title>
<?php
include 'head.php';
?>
</head>
<body>
<?php
include 'nav.php';
?>
<div id="wrapper">
<div id="content">
<?php
include 'connect.php';
function generateRandomString($length = 20) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

function failure($error){
	echo "Oops... We don't know what the error is, but it is indeed one.... :(";
	die();
}

//details
if(!isSet($_POST['name']) || !isSet($_POST['email'])){die();}
$name = $_POST['name'];
$email = $_POST['email'];
$time = time();
$verStr = generateRandomString();

mysql_select_db($db, $con);
$query = "SELECT verificationcode, isverified FROM subscribers WHERE email = '{$email}'";
$result = mysql_query($query) or failure(mysql_error());
if(mysql_num_rows($result) != 0){
	$row = mysql_fetch_row($result);
	if($row[1] == true){
		echo "You are already subscribed to my site!";
		die();
	}
	
	$verStr = $row[0];
} else {
	$query  = "INSERT INTO subscribers VALUES('{$name}', '{$email}', '{$verStr}', false, {$time})";
	$result = mysql_query($query) or failure(mysql_error());
}
mysql_close($con);

//create urls
$fullurl = "http://craftntalk.com/verify.php?code=".$verStr."&email=".urlencode($email);
$halfurl = "http://craftntalk.com/verify.php?email=".urlencode($email);
////////send mail
$mail_subject    = "Craft and Talk : Verification"; 

$mail_message    = "<p>Hi {$name}, </p>"
					."<p>Thanks for your interest. To confirm your subscription please click on the button below:</p>"
					."<p><a href='{$fullurl}' style='padding:5px;background-color:#0c2289;color:white;border-radius:5px;text-decoration:none'>Activate</a></p>"
					."<p>OR</p>"
					."<p>Go to <a href='{$halfurl}'>{$halfurl}</a> and paste the following code into the box:</p>"
					."<p><strong>{$verStr}</strong></p>";

$mail_headers    = "From: webmaster@".$_SERVER['SERVER_NAME'] . "\r\n". 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$mail_parameters = ""; 

ini_set('sendmail_from',"webmaster@".$_SERVER['SERVER_NAME']); 

$result = mail($email,$mail_subject,$mail_message,$mail_headers,$mail_parameters); 

////////////

echo "<h2>Thank you for subscribing</h2><p>Please check your mail (don't forget the spam folder!) for our verification email.</p>";
?>
</div>
</div>
<?php
include 'footer.php';
?>
</body>
</html>